import json
import math
import re
import time
from datetime import datetime
import requests

from log_time_sleeps.execl import Excel_xrlts


class Alarms_Execl:
    def __init__(self, zhi):
        self.__dict__.update(zhi)
        super().__init__()
        self.get_can()
        self.session = requests.session()

    def Alarms_Execl_can(self):
        self.my_logg.info(f'{self.name}智能网管平台正在查询是否有写入的文档...')
        start_time = time.time()
        cookies = {
            'accessToken': self.accessToken,
        }
        response = self.session.get(url=self.url + '/alarmQuery1/sys/alarmOrder/listTaskQueryToTianyan',
                                    headers=self.headers, params=self.params, cookies=cookies, verify=False)
        if response.status_code == 200:
            response_dict = []
            response_cyt = response.json()
            data = response_cyt['data']
            workbook_name='运维工单'
            self.xrlts = Excel_xrlts(svn_path=self.svn_path)
            self.data_list,sheet=self.xrlts.xlsx_read(workbook_name=workbook_name)
            for i in reversed(range(0, int(response_cyt['total']), 40)):
                self.params['offset'] = str(i)
                response = self.session.get(url=self.url + '/alarmQuery1/sys/alarmOrder/listTaskQueryToTianyan',
                                            headers=self.headers, params=self.params, cookies=cookies, verify=False)
                response_cyt = response.json()['data']
                for response_in in reversed(response_cyt):
                        pid = {"pid": response_in['pid']}
                        self.session.headers['Content-Type'] = 'application/json; charset=utf-8'
                        response = self.session.post(url=self.url + '/alarmQuery1/sys/alarmOrder/taskInfoListHandle',
                                                     data=json.dumps(pid), verify=False)
                        if response.status_code == 200:
                            response = response.json()['alarmOrder']
                            alarmOrderId = response['alarmOrderId']
                            if alarmOrderId not in self.data_list:
                                zhi=self.get_alarm_order_id(response)
                                response_dict.append(zhi)
                            else:
                                xlsx_search,cell_row=self.xrlts.xlsx_search(sheet=sheet,value=alarmOrderId)
                                if xlsx_search:
                                    zhi = self.get_alarm_order_id(response)
                                    if not xlsx_search[-3] and not xlsx_search[-4] and  zhi[-3]  and zhi[-4]:
                                        self.xrlts.xlsx_update(sheet=sheet,new_values=zhi,row_index=cell_row)

            self.xrlts.xlsx_copy(xlsx_dict=response_dict, data_list=self.data_list,sheet=sheet)
            end_time = time.time()
            self.my_logg.info("新物联网监控告警工单已生成完毕: {:.2f} 秒".format(end_time - start_time))
        else:
            self.my_logg.info(f'{self.name}智能网管平台cookie可能失效')

    def get_alarm_order_id(self, respone):
        respones_keywords = ["关闭", "忽略", "屏蔽", "处理意见"]
        alarmOrderId1 = respone["alarmOrderId"]
        keywords = re.findall(r'GATEWAY|Gateway|CMP|DMP|实名制|云网|SAAS|Multipod|动环系统', respone["system"])
        system2 = ' '.join(keywords)
        # 根据关键词确定最终值
        if 'GATEWAY' in system2 or 'Gateway' in system2:
            system2 = 'Gateway'
        elif '云网' in system2:
            system2 = '云底座'
        elif 'SAAS' in system2:
            system2 = 'DMP'
        elif '动环系统' in system2:
            system2 = '动环'
        alarmOrderInfo3 = respone["alarmOrderInfo"]
        level4 = respone["level"]
        message = respone["message"]
        y = message.split('\n')
        list_c = [x.strip().replace("  ", " ") for x in y if x.strip() != '']
        match=result_s=result_sign_s=result_close_s= None
        for lists in list_c:
            if any(keyword in lists for keyword in respones_keywords):
                result_close_s = lists[:lists.find('处理意见：')] if '处理意见：' in lists else lists
                match = re.findall(r'处理意见：(.*)', lists) or re.findall(r'系统\s+自动关闭', lists) or re.findall(r'noc\s+解决关闭', lists)
            elif '已签收' in lists:
                result_sign_s = lists
            elif '告警发起' in lists:
                result_s = lists
        result_sign_s=result_sign_s if result_sign_s else ''
        match = match[0] if match else ''
        pattern = r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
        # 提取日期时间部分并转换为 datetime 对象
        y_datetime = datetime.strptime(re.search(pattern, result_sign_s).group(),
                                       '%Y-%m-%d %H:%M:%S') if result_sign_s else ''
        x_datetime = datetime.strptime(re.search(pattern, result_s).group(), '%Y-%m-%d %H:%M:%S')
        # 转换为分钟并向上取整到最接近的整数
        minutes = str(math.ceil((y_datetime - x_datetime).total_seconds() / 60)) + '分钟之内' if result_sign_s else ''
        return [
            alarmOrderId1,
            system2,
            alarmOrderInfo3,
            level4,
            result_s, result_sign_s, minutes, result_close_s, result_close_s, None,
            match
        ]




    def get_can(self):
        self.headers = {
            'Accept': 'application/json',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Connection': 'keep-alive',
            'Content-Type': 'application/json; charset=utf-8',
            'Referer': self.url + '/alarmOrderCount/alarmsHandle',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
            'accessToken': self.accessToken,
            'userName': 'bm9j',
        }
        self.params = {'offset': '0', 'limit': '40', 'alarmOrderId': '', 'system': 'ALL', 'module': 'ALL',
                       'alarmOrderInfo': '', 'alarmNextDealTag': '', 'level': '', 'startTime': self.startTime,
                       'endTime': self.end_time, 'userId': '99999808'}